package com.fsmv.canwild;

import java.text.ParseException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class main extends Activity {
	public static final int ALARM = 1;
	public static final int SET_RINGTONE = 255;
	public static final String PREFS_NAME = "AlarmTime";
	
	private SharedPreferences settings;
	private SharedPreferences.Editor settingsEditor;
	private TimePicker time;
	private TextView display;
	private CheckBox enabled;
	private CheckBox notification;
	private EditText length;
	
	private AlarmManager alarmManager;
	private PendingIntent pendingIntent;
	private Calendar date;
	private Intent alarmIntent;
	private Button ring;
	
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        display = (TextView) findViewById(R.id.textView);
        time = (TimePicker) findViewById(R.id.timePicker);
        enabled = (CheckBox) findViewById(R.id.checkBox);
        notification = (CheckBox) findViewById(R.id.checkBox1);
        length = (EditText) findViewById(R.id.editText1);
        ring = (Button) findViewById(R.id.button1);
        alarmIntent = new Intent(this, AlarmReceiver.class);
        settings = getSharedPreferences(PREFS_NAME, 0);
        settingsEditor = settings.edit();
        
        if(enabled != null){
        	enabled.setOnCheckedChangeListener(new OnCheckedChangeListener(){
				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
					if(!isChecked){
						display.setText("Alarm Disabled");
			    		alarmManager.cancel(pendingIntent);
					}
					settingsEditor.putBoolean("enabled", isChecked);
				}
        	});
        }
        
        if(notification != null){
        	notification.setOnCheckedChangeListener(new OnCheckedChangeListener(){
        		@Override
        		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
        			updateNotification(isChecked);
        			settingsEditor.putBoolean("notification", isChecked);
        		}
        	});
        }
        
        checkSettings();
        
        date = Calendar.getInstance();
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    }
    
    @Override
    public void onPause(){
    	super.onPause();
    	settingsEditor.commit();
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	checkSettings();
    }
    
    public void checkSettings(){
    	//Set notification check box
    	updateNotification(settings.getBoolean("notification", false));
    	notification.setChecked(settings.getBoolean("notification", false));
    	
    	//Set enabled check box
    	enabled.setChecked(settings.getBoolean("enabled", false));
    	
    	//Set ring tone
    	String us = settings.getString("ringtone", "null");
    	if(us != "null"){
    		Uri r = Uri.parse(us);
    		setRingtone(r);
    	}else{
    		ring.setText("Silent");
    	}
    	
    	//Set ring length
    	length.setText(Integer.toString(settings.getInt("length", 3)));
    	
    	//Set the alarm display at the top
    	int hours = settings.getInt("hours", -1);
    	int minutes = settings.getInt("minutes", -1);
    	Log.d("alarm", hours + ":" + minutes);
    	Log.d("alarm", settings.getString("ringtone", "null"));
    	Log.d("alarm", ""+settings.getBoolean("notification", false));
    	Log.d("alarm", ""+settings.getBoolean("enabled", false));
    	Log.d("alarm", ""+settings.getInt("length", 3));
    	Log.d("alarm", "break");
        if(hours != -1 && minutes != -1){
        	if(settings.getBoolean("enabled", false)){
        		String h = hours < 10 ? "0" +Integer.toString(hours): Integer.toString(hours); 
				String m = minutes < 10 ? "0" +Integer.toString(minutes) : Integer.toString(minutes);
        		display.setText("Alarm set for " + h + ":" + m + " (repeats daily)");
        	}
        		//Set the time picker display
        	time.setCurrentHour(hours);
    		time.setCurrentMinute(minutes);
        }
    }
    
    public void buttonHandler(View v){
    	if(v.getId() == R.id.button){
    		updateDisplay();
    	}else if(v.getId() == R.id.button1){
    		requestRingtone();
    	}
    }
    
    public void requestRingtone(){
    	Intent intent = new Intent( RingtoneManager.ACTION_RINGTONE_PICKER);
        intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_ALARM);
        intent.putExtra( RingtoneManager.EXTRA_RINGTONE_TITLE, "Select Tone");
        intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri)null);
        
        startActivityForResult(intent, SET_RINGTONE);
    }
    
    public void updateDisplay() {
    	if(enabled.isChecked()){
    		pendingIntent = PendingIntent.getBroadcast(this, ALARM, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    		if(length.getText().toString() != "")
    			setRingLength(Integer.parseInt(length.getText().toString()));
    		String h = time.getCurrentHour() < 10 ? "0" +Integer.toString(time.getCurrentHour()): Integer.toString(time.getCurrentHour()); 
    		String m = time.getCurrentMinute() < 10 ? "0" +Integer.toString(time.getCurrentMinute()) : Integer.toString(time.getCurrentMinute());
    		settingsEditor.putInt("hours", time.getCurrentHour());
    		settingsEditor.putInt("minutes", time.getCurrentMinute());
    		long alarmMillis = System.currentTimeMillis();
    		try{
    			alarmMillis = new java.text.SimpleDateFormat ("MM/dd/yyyy HH:mm:ss").parse(((date.get(Calendar.MONTH)+1) < 10 ? "0"+(date.get(Calendar.MONTH)+1) : (date.get(Calendar.MONTH)+1)) +"/"+ (date.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + date.get(Calendar.DAY_OF_MONTH): date.get(Calendar.DAY_OF_MONTH)) +"/" + date.get(Calendar.YEAR) + " " + h + ":"+m+":00").getTime();
    		}catch(ParseException e){}
    		display.setText("Alarm set for " + h + ":" + m + " (repeats daily)");
    		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmMillis, 24*60*60*1000, pendingIntent);
    		Toast.makeText(this, "Alarm set " + ((date.get(Calendar.MONTH)+1) < 10 ? "0"+(date.get(Calendar.MONTH)+1) : (date.get(Calendar.MONTH)+1)) +"/"+ (date.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + date.get(Calendar.DAY_OF_MONTH): date.get(Calendar.DAY_OF_MONTH)) +"/" + date.get(Calendar.YEAR) + " " + h + ":"+m+":00" , Toast.LENGTH_LONG).show();
    	}else{
    		display.setText("Alarm Disabled");
    		alarmManager.cancel(pendingIntent);
    	}
    }
    
    public void updateNotification(boolean b){
    	alarmIntent.putExtra("notification", b);
    	settingsEditor.putBoolean("notification", b);
    }
    
    public void setRingtone(Uri uri){
    	Ringtone t = RingtoneManager.getRingtone(this, uri);
    	String title = "Silent";
    	if(t != null)
    		title = t.getTitle(this);
    	ring.setText(title);
    	alarmIntent.putExtra("uri", uri.toString());
    	settingsEditor.putString("ringtone", uri.toString());
    }
    
    public void setRingLength(int len){
    	alarmIntent.putExtra("length", len);
    	settingsEditor.putInt("length", len);
    }
    
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data){
    	super.onActivityResult(requestCode, resultCode, data);
    	if (resultCode == RESULT_OK && requestCode == SET_RINGTONE) {
    		Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
    		if (uri != null)
    			setRingtone(uri);
    	}
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.about:
        		Intent intent = new Intent(this, About.class);
        		startActivity(intent);
        	break;
        default:
        	return super.onOptionsItemSelected(item);
        }
		return super.onOptionsItemSelected(item);
    }
}